package main

import (
	"fmt"
	"math/rand"
	"sort"
	"strings"
)

/*
map操作
*/

func main() {
	// 定义一个map map[KeyType]ValueType
	var scoreMap map[string]int
	// 初始化map
	scoreMap = make(map[string]int, 8)
	scoreMap["张三"] = 90
	scoreMap["李四"] = 100
	fmt.Println(scoreMap)
	fmt.Printf("scoreMa type is :  %T\n", scoreMap)
	//转成清晰的结构
	fmt.Printf("scoremap is : %#v\n", scoreMap)

	// 定义并初始化一个map
	nameAge := map[string]string{
		"ssc": "18",
		"hdd": "19",
	}
	fmt.Println(nameAge)
	// 查询key 在不在
	v, ok := nameAge["hdd"]
	if ok {
		fmt.Println(v)
	} else {
		fmt.Println("查无此人")
	}
	// 遍历map key,value
	fmt.Println("遍历map : ")
	for key, value := range nameAge {
		fmt.Println("key is : ", key, ", value is : ", value)
	}
	// 遍历 map 下所有key
	fmt.Println("只遍历key ")
	for k := range nameAge {
		fmt.Println(k)
	}
	// 遍历map中所有的value
	for _, v := range nameAge {
		fmt.Printf("只遍历所有的值打印 : %s\n", v)
	}

	// 删除键值对
	delete(nameAge, "hdd")

	fmt.Println(nameAge)
	fmt.Println()

	/* 按照某个固定的顺序遍历map*/
	var ssMap = make(map[string]int)

	for i := 1; i < 51; i++ {
		key := fmt.Sprintf("stu%02d", i)
		value := rand.Intn(101)
		ssMap[key] = value
	}
	fmt.Println(len(ssMap))
	for k, v := range ssMap {
		fmt.Println(k, v)
	}
	/*
		将map中的键值对按照指定的顺序进行排序
		按照map中的key 进行从小到达的排序
		1. 先取出所有的key 存放到切片中
		2. 对key进行排序
		3. 按照排序好的key 对map 进行排序
	*/
	keys := make([]string, 0, 100)
	for k := range ssMap {
		keys = append(keys, k)
	}
	fmt.Println(keys, "111")
	sort.Strings(keys)
	fmt.Println("sorter keys is ", keys)
	// 遍历map
	fmt.Println("按照顺序遍历")
	for _, key := range keys {
		fmt.Println(key, ssMap[key])
	}

	//fmt.Printf("ssMap is : %#v\n", ssMap)

	/*
		特殊格式的map
	*/
	// 元素为map的切片
	var mapSlice = make([]map[string]string, 3)
	for index, value := range mapSlice {
		fmt.Printf("index:%d value:%v\n", index, value)
	}
	fmt.Println("after init")
	// 对切片中的map元素进行初始化
	mapSlice[0] = make(map[string]string, 10)
	mapSlice[0]["name"] = "小王子"
	mapSlice[0]["password"] = "123456"
	mapSlice[0]["address"] = "沙河"
	fmt.Println(mapSlice)
	for index, value := range mapSlice {
		fmt.Printf("index:%d value:%#v\n", index, value)
	}
	fmt.Println()
	// 值为切片的map
	var sliceMap = make(map[string][]string)

	// 初始化slice
	sliceMap["中国"] = make([]string, 5)
	sliceMap["中国"][0] = "北京"
	sliceMap["中国"][1] = "上海"
	sliceMap["中国"][2] = "合肥"
	for k, v := range sliceMap {
		fmt.Printf("key : %v value : %#v\n", k, v)
	}

	// 统计字符串中 字符出现的次数
	/*
		how do you do
		分析:

	*/

	var s = "how do you do"
	//1。创建一个map 记录单词和出现的次数
	var wordCount = make(map[string]int)
	// 切割字符串
	words := strings.Split(s, " ")
	fmt.Println("words is :", words)

	for _, word := range words {
		v, ok := wordCount[word]
		if ok {
			wordCount[word] = v + 1
		} else {
			wordCount[word] = 1
		}
	}
	for key, value := range wordCount {
		fmt.Println(key, value)
	}

}
